package services

import (
	"encoding/hex"
	"encoding/binary"
	"time"
	."ircove.com/common"
)

func TokenDecode(client_id string,token string) (int32,error) {

	if len(token) !=32{
		return -1, ErrorArgument.Clone("token len is error")
	}

	bytes,err :=	hex.DecodeString(token)
	if err!=nil {
		return -1, err
	}
	expiretime:= binary.LittleEndian.Uint32(bytes[0:4])

	var now = time.Now().Unix();
	if uint32(now) > expiretime {
		return -1, ErrorArgument.Clone("token is timeout")
	}

	userid := binary.LittleEndian.Uint32(bytes[4:8]);

	client_id_hash:= binary.LittleEndian.Uint32(bytes[8:12])
	var hash = FNVHash(client_id, int32( expiretime ^ userid));
	if  hash != int32(client_id_hash){

		return -1, ErrorArgument.Clone("token formet is error")
	}
	cr32:=int32(binary.LittleEndian.Uint32(bytes[12:16]))
	for i:=12;i<16;i++  {
		bytes[i]=0
	}
	sign:= CalcCRC32(bytes)
	if cr32 !=sign {
		return -1, ErrorArgument.Clone("token formet is error")
	}
	return int32(userid) ,nil
}
